package com.egobuy.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egobuy.entity.Item;
import com.egobuy.entity.ItemDesc;
import com.egobuy.pojo.BuyResult;
import com.egobuy.pojo.EgoBuyPager;
import com.egobuy.product.mapper.ItemDescMapper;
import com.egobuy.product.mapper.ItemMapper;
import com.egobuy.product.service.IItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author Hello
 * @since 2021-11-22
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private FreeMarkerConfigurer configurer;
    @Override
    public BuyResult<EgoBuyPager<Item>>  queryByPage(int page, int size, Item item) {
        EgoBuyPager<Item> pager=new EgoBuyPager<>();
        //当前页
        pager.setCurrent(page);
        //
        pager.setSize(size);
        //
        QueryWrapper<Item> queryWrapper=new QueryWrapper();
        if(item != null) {
            if(item.getTitle()!=null && !"".equals(item.getTitle())) {
                queryWrapper.like("title", "%" + item.getTitle() + "%");
            }
            if(item.getStatus()!=null && item.getStatus()!=0) {
                queryWrapper.eq("status", item.getStatus());
            }
        }
        pager = itemMapper.selectPage(pager, queryWrapper);//页数

        // 页面的开始位置和结束位置没有，需要计算
        long maxPageNum =  pager.getPages();;
        int pageStart = 1;
        int pageEnd = 10;
        if(page - 4 > 1){
            pageStart = page - 4;
        }
        if(page + 5 > maxPageNum){
            pageEnd = (int) maxPageNum;
        }
        pager.setPageStart(pageStart);
        pager.setPageEnd(pageEnd);

        BuyResult<EgoBuyPager<Item>> result = BuyResult.ok();
        result.setData(pager);
        return result;
    }

    @Override
    public BuyResult save(Item item, ItemDesc itemDesc) {
        // id 自增
        item.setId(new Long(redisTemplate.opsForValue().increment("itemId")));

        Date date=new Date();
        item.setCreated(date);
        item.setUpdated(date);
        item.setStatus(1);

        itemMapper.insert(item);

        //
        itemDesc.setItemId(item.getId());
        itemDesc.setCreated(date);
        itemDesc.setUpdated(date);

        itemDescMapper.insert(itemDesc);
        return BuyResult.ok();
    }

    @Override
    public BuyResult<Map> queryDetail(long itemId) {
        // 准备数据
        Map map = new HashMap();
        // 查询商品信息
        Item item = itemMapper.selectById(itemId);
        map.put("item",item);
        if (item!=null&& StringUtils.isNotBlank(item.getImage())){
            String image=item.getImage();
            String[] images = image.split(";");
            if (images!=null&&images.length>0){
                //  处理图片信息
                item.setImage(images[0]);
            }
            //将列表也放入map
            map.put("images",images);
        }
        //将列表也放入map
        // 查询详情信息

        ItemDesc itemDesc = itemDescMapper.selectById(itemId);
        map.put("itemDesc",itemDesc);
        return  BuyResult.ok(map);
    }

    @Value("${static-path}")
    private String staticPath;
    @Override
    public BuyResult itemStatic(long itemId) {
        // 根据id查询商品
        // 准备数据
        Map map = new HashMap();
        // 查询商品信息
        Item item = itemMapper.selectById(itemId);
        map.put("item",item);
        //  处理图片信息
        if(item!=null && StringUtils.isNotBlank(item.getImage())){
            String image = item.getImage();
            String[] images = image.split(";");
            if(images!=null && images.length>0){
                item.setImage(images[0]);
            }
            //将列表也放入map
            map.put("images",images);
        }
        // 查询详情信息
        ItemDesc itemDesc = itemDescMapper.selectById(itemId);
        map.put("itemDesc",itemDesc);

        //使用freemarker进行静态化处理
        Configuration configuration = configurer.getConfiguration();
        Writer writer=null;
        try {
            Template template = configuration.getTemplate("item.ftlh");
            writer = new FileWriter(staticPath+itemId+".html");
            template.process(map,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer!=null) {
                    writer.close();
                }
            }catch (Exception ex){
                ex.printStackTrace();;
            }
        }

        return BuyResult.ok();
    }
}
